<template>
  <div class="show-visitor">
    <div class="show">
      <div class="titleImage">
        <img
          ref="titleImgRef"
          style="width: 100%"
          src="./icon/top.svg"
          alt=""
          @load="imageLoad"
        >

        <div class="setting-icon" @click="settingDrawerShow = true">
          <i class="el-icon-setting" />
        </div>

      </div>
      <div style="width: 100%; display: flex; justify-content: center">
        <div class="first" :style="{ height: `${calculateHeight}vh` }">
          <div ref="headerRef" class="list-header">
            <div class="people-list-title">
              <div style="margin-left: 10px;">
                <template v-if="settingValue.showPageChangeButton">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="manualChangePage('prevPage')"
                  >
                    上一页
                  </el-button>

                  <el-button
                    size="mini"
                    type="primary"
                    @click="manualChangePage('nextPage')"
                  >
                    下一页
                  </el-button>
                </template>

                <template v-if="settingValue.showListTypeChangeButton">
                  <el-dropdown @command="handleChangeListType">
                    <div class="dropdown-btn">
                      {{ dropdownBtnText }}<i class="el-icon-arrow-down el-icon--right" />
                    </div>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        v-for="(item, index) in listTypes"
                        :key="index"
                        :command="item.value"
                      >
                        {{ item.label }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>

              </div>
              <div style="flex: 1;" />
              <div class="list-title">
                {{ listTitle[listType] }}
              </div>
              <div class="play-icon" @click="changeScrollState">
                <i
                  style="font-size: 26px;"
                  :class="[
                    isPlaying ? 'el-icon-video-pause' : 'el-icon-video-play'
                  ]"
                />
              </div>

            </div>
            <div style="width: 100%">
              <NoticeBar
                ref="noticeBar"
                :style="buildNoticeBarStyle"
                :list="noticeFormatted"
                :speed="noticeFormatted.length * 60"
                @clearNoticeList="resetNoticeList"
              />
            </div>
            <div v-if="listType === 'visitor'" class="swiper-title">
              <div class="visitor-title" style="width: 20%; flex: none">公司名称</div>
              <div class="visitor-title" style="width: 20%; flex: none">来访人员</div>
              <div class="visitor-title" style="width: 10%; flex: none">接待人</div>
              <div class="visitor-title" style="width: 10%; flex: none">人数</div>
              <div class="visitor-title" style="width: 20%; flex: none">联系电话</div>
              <div
                class="visitor-title"
                style="transition: all 0.5s; width: 20%; flex: none"
                @click="openTimePicker"
              >
                <el-date-picker
                  ref="timePick"
                  v-model="time"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  class="timePick"
                  :picker-options="pickerOptions"
                  @change="timeChange"
                />
                访问时间

                <div>
                  <i
                    class="el-icon-caret-bottom"
                    style="color: #00fff4; font-size: 1.5vw"
                  />
                  <i
                    title="重置"
                    class="el-icon-refresh"
                    :class="{ rotate: loading || !showList }"
                    style="color: #00fff4; font-size: 1.5vw"
                    @click.stop="reset"
                  />
                </div>
              </div>
            </div>

            <div v-if="listType === 'vehicleRecord'" class="swiper-title">
              <div class="visitor-title" style="width: 16%; flex: none">申请人</div>
              <div class="visitor-title" style="width: 16%; flex: none">车牌号</div>
              <div class="visitor-title" style="width: 16%; flex: none">用车时间</div>
              <div class="visitor-title" style="width: 10%; flex: none">司机</div>
              <div class="visitor-title" style="width: 21%; flex: none">用车路线</div>
              <div class="visitor-title" style="width: 21%; flex: none">用车原因</div>
            </div>

            <div v-if="listType === 'conferenceRoom'" class="swiper-title">
              <div class="visitor-title" style="width: 20%; flex: none">预约人</div>
              <div class="visitor-title" style="width: 20%; flex: none">会议室</div>
              <div class="visitor-title" style="width: 30%; flex: none">使用时间</div>
              <div class="visitor-title" style="width: 30%; flex: none">使用原因</div>
            </div>
          </div>

          <div
            v-show="visitorList.length > 0 && showList"
            ref="listRef"
            class="list-warp"
            :style="{ height: `${calculateListHeight}vh` }"
          >
            <div
              v-for="(item) in visitorList"
              :key="item.id"
              ref="recordItems"
              class="list"
            >
              <template v-if="listType === 'visitor'">
                <span
                  style="width: 20%; flex: none"
                  :title="item.company_name"
                  class="visitor-content"
                >
                  {{ item.company_name }}
                </span>

                <span
                  style="width: 20%; flex: none"
                  :title="item.visitor_position ? `${item.visitor}(${item.visitor_position})` : item.visitor"
                  class="visitor-content"
                >
                  <template v-if="!item.visitor_position">
                    {{ item.visitor }}
                  </template>

                  <template v-else>
                    {{ item.visitor }}({{ item.visitor_position }})
                  </template>
                </span>

                <span
                  style="width: 10%; flex: none"
                  :title="item?.docking?.username"
                  class="visitor-content"
                >
                  {{ item?.docking?.username }}
                </span>
                <span
                  :title="item.fellow"
                  style="width: 10%; flex: none"
                  class="visitor-content"
                >{{ item.fellow }}</span>
                <span
                  :title="item.phone"
                  class="visitor-content"
                  style="width: 20%; flex: none"
                >{{ item.phone }}</span>
                <span
                  :title="item.arrive_time"
                  class="visitor-content"
                  style="width: 20%; flex: none"
                >
                  {{ item.arrive_time }}
                </span>
              </template>

              <template v-if="listType === 'vehicleRecord'">
                <span
                  :title="item?.user?.username"
                  style="width: 16%; flex: none"
                  class="visitor-content"
                >{{ item?.user?.username ?? '-' }}</span>
                <span
                  :title="item?.vehicle?.license_plate_number"
                  style="width: 16%; flex: none"
                  class="visitor-content"
                >{{ item?.vehicle?.license_plate_number ?? '-' }}</span>
                <span
                  :title="item?.vehicle_usage_time"
                  style="width: 16%; flex: none"
                  class="visitor-content"
                >{{ item?.vehicle_usage_time ?? '-' }}</span>
                <span
                  v-if="item.driver_type === 'driver' || item.driver_type === 'notSelf'"
                  :title="item?.driver_user?.username"
                  style="width: 10%; flex: none"
                  class="visitor-content"
                >{{ item?.driver_user?.username ?? '-' }}</span>
                <span
                  v-else
                  :title="item?.user?.username"
                  style="width: 10%; flex: none"
                  class="visitor-content"
                >{{ item.driver_type === 'self' ? item?.user?.username : '-' }}</span>
                <span
                  :title="item?.vehicle_route"
                  style="width: 21%; flex: none"
                  class="visitor-content of"
                >{{ item?.vehicle_route ?? '-' }}</span>
                <span
                  :title="item?.car_reason"
                  style="width: 21%; flex: none"
                  class="visitor-content of"
                >{{ item?.car_reason ?? '-' }}</span>
              </template>

              <template v-if="listType === 'conferenceRoom'">
                <ReserveList
                  :item="item"
                />
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-drawer
      :visible.sync="settingDrawerShow"
      size="20%"
    >
      <template #title>
        <div class="setting-title">设置</div>
      </template>
      <div class="setting-drawer">
        <div class="setting-drawer__item">
          <span class="setting-drawer__item-title">自动切换页码</span>
          <el-switch
            v-model="settingValue.autoPaging"
            @change="($event) => settingValueChange($event, 'autoPaging')"
          />
        </div>
        <div class="setting-drawer__item">
          <span class="setting-drawer__item-title">自动切换列表类型</span>
          <el-switch
            v-model="settingValue.autoChangeType"
            @change="($event) => settingValueChange($event, 'autoChangeType')"
          />
        </div>

        <div class="setting-drawer__item">
          <span class="setting-drawer__item-title">展示页码切换按钮</span>
          <el-switch
            v-model="settingValue.showPageChangeButton"
            @change="($event) => settingValueChange($event, 'showPageChangeButton')"
          />
        </div>

        <div class="setting-drawer__item">
          <span class="setting-drawer__item-title">展示列表类型切换按钮</span>
          <el-switch
            v-model="settingValue.showListTypeChangeButton"
            @change="($event) => settingValueChange($event, 'showListTypeChangeButton')"
          />
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { today, out } from '@/api/visitor'
import { bind } from '@/api/v2/visitor'
import dayjs from 'dayjs'
import { atLeast, get } from '@/utils/kris_utils'
import NoticeBar from '@/components/NoticeBar/NoticeBar2.vue'
import { debounce } from 'lodash'
import { getTodayAndAfterVehicleRecord } from '@/api/vehicleService'
import ReserveList from '@/views/visitor/components/show/ReserveList.vue'
import { getReserveList } from '@/api/conferenceRoom'

const fieldChineseMap = {
  visitor: '来访人员',
  company_name: '公司名',
  phone: '联系电话',
  fellow: '同行人员数量',
  docking_id: '对接人员',
  // department_id: '部门',
  arrive_time: '访问时间'
}

// const INTERVAL_LENGTH = 5
const LIMITMOVENUM = 5
const CLIENT_ID = 'client_id'
export const SETTING_KEY = 'setting'
export default {
  components: {
    // vueSeamlessScroll,
    NoticeBar,
    ReserveList
  },
  data() {
    return {
      listTitle: {
        visitor: '访客列表',
        vehicleRecord: '用车列表',
        conferenceRoom: '会议室预约列表'
      },
      settingDrawerShow: false,
      settingValue: {
        autoPaging: true,
        autoChangeType: false,
        showPageChangeButton: true,
        showListTypeChangeButton: true
      },
      gc: {
        timer: null
      },
      websocket: {
        instance: null,
        state: 'INITAL',
        lastReceived: null,
        sinceLastSent: null, // 无用，预留
        checkerTimer: null,
        heartbeatInterval: 1000 * 30 + (1000 * 10) // 多出来的5秒算误差时间
      },
      autoScroll: {
        timer: null
      },
      autoRefresh: {
        timer: null
      },
      channel: null,
      notices: [],

      record: [],
      leave: [],
      timer: null,
      date: '',
      weekday: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      week: '',
      day: '',
      time: '',
      loading: false,
      show: false,
      setIntervalTimer: null,
      page: {
        pageSize: 99,
        currentPage: 1,
        total: 0
      },
      imageHeight: 0,
      viewportHeight: 0,
      showList: false,
      isPlaying: true,
      listType: 'visitor',
      listTypeTimer: null,
      listTypes: [
        { value: 'visitor', label: '查看访客记录' },
        { value: 'vehicleRecord', label: '查看用车记录' },
        { value: 'conferenceRoom', label: '查看会议室预约记录' }
      ]
    }
  },
  computed: {
    noticeFormatted() {
      return this.notices.map((item, index) => {
        return this.noticeTextFormat(
          {
            ...item,
            docking_id: get(item, 'docking_id.username')
            // arrive_time: this.timeFormat(item.arrive_time)
          },
          index
        )
      })
    },
    buildNoticeBarStyle() {
      return {
        transition: 'all 1s',
        height: this.notices.length > 0 ? '10vh' : '0',
        padding: this.notices.length > 0 ? '10px' : '0'
      }
    },
    defaultOption() {
      return {
        step: 0.5,
        limitMoveNum: LIMITMOVENUM,
        hoverStop: true
      }
    },
    pickerOptions() {
      return {
        disabledDate: (time) => {
          const today = new Date()
          return time.getTime() < today.setHours(0, 0, 0, 0)
        }
      }
    },
    visitorList() {
      const start = (this.page.currentPage - 1) * this.page.pageSize
      const end = start + this.page.pageSize
      return this.record.slice(start, Math.min(end, this.page.total))
    },
    totalPage() {
      const { pageSize, total } = this.page
      return Math.ceil(total / pageSize)
    },
    hasNextPage() {
      const { currentPage } = this.page
      return currentPage < this.totalPage
    },
    calculateHeight() {
      const imageHeight = (this.imageHeight / this.viewportHeight) * 100
      return 100 - imageHeight - 5
    },
    calculateListHeight() {
      const listHeaderHeight = this.$refs?.headerRef?.clientHeight
      // const lh = (this.calculateHeight * this.viewportHeight) / 100
      const headerVh = (listHeaderHeight / this.viewportHeight) * 100
      return this.calculateHeight - headerVh
    },

    isVisitor() {
      return this.listType === 'visitor'
    },

    dropdownBtnText() {
      const btnTextMap = {
        visitor: '查看访客记录',
        vehicleRecord: '查看用车记录',
        conferenceRoom: '查看会议室预约记录'
      }

      return btnTextMap[this.listType]
    }
  },
  watch: {
    viewportHeight: {
      immediate: true,
      handler() {
        const loading = this.$loading({
          lock: true,
          text: '加载中......',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, .8)'
        })
        Promise.all([
          // this.showToday(),
          this.getList(),
          this.calculateItemsPerPage()
        ])
        setTimeout(() => {
          loading.close()
        }, 300)
      }
    }
  },
  created() {
    window.test = this

    this.showOut()
    this.openWs()
    this.startWsChecker()

    this.startAutoRefresh()
    this.initSettings()
    // this.changeListTypeStart()
  },
  mounted() {
    // this.showToday()
    this.getList()
    this.viewportHeight = window.innerHeight
    this.getViewportHeight()
    this.nowDate()
    console.log(this.$route.query.company_id, 666666)
    // this.calculateItemsPerPage()
  },
  beforeDestroy() {
    this.closeWs()
    this.stopWsChecker()
    this.stopAutoRefresh()
    this.stopAutoScroll()
  },
  methods: {
    handleChangeListType(e) {
      console.log('e --------->', e)
      this.changeListTypeStop()
      this.changeListTypeStart()

      this.listType = e
      this.reset()
    },
    changeListTypeStart(delay = 1000 * 60) {
      if (!this.settingValue.autoChangeType) return
      this.changeListTypeStop()
      this.listTypeTimer = setInterval(() => {
        this.changeListType(false)
      }, delay)
    },

    changeListTypeStop() {
      if (typeof this.listTypeTimer !== 'number' || isNaN(this.listTypeTimer)) { return }
      clearInterval(this.listTypeTimer)
    },

    changeListType(isClick = true) {
      if (isClick) {
        this.changeListTypeStop()
        this.changeListTypeStart()
      }

      if (this.listType === 'visitor') {
        this.listType = 'vehicleRecord'
      } else if (this.listType === 'vehicleRecord') {
        this.listType = 'conferenceRoom'
      } else if (this.listType === 'conferenceRoom') {
        this.listType = 'visitor'
      }

      this.reset()
    },

    changeScrollState() {
      if (this.isPlaying) this.stopAutoScroll()
      else this.startAutoScroll()
      this.isPlaying = !this.isPlaying

      // this.isPlaying ? this.stopAutoScroll() : this.startAutoScroll()
    },
    async calculateItemsPerPage() {
      this.page = this.$options.data().page
      await this.sleep(1000)
      this.showList = false
      const listHeightPx = (this.calculateListHeight * this.viewportHeight) / 100
      let totalHeight = 0
      let itemsPerPage = 0
      for (let i = 0; i < this.record.length; i++) {
        const itemHeight = this.$refs.listRef?.children[i]?.clientHeight
        totalHeight += itemHeight

        if (totalHeight <= listHeightPx) {
          itemsPerPage++
        } else {
          break
        }
      }
      this.page.pageSize = itemsPerPage
      this.showList = true
    },

    getViewportHeight() {
      window.addEventListener('resize', debounce(() => {
        this.viewportHeight = window.innerHeight
      }, 1000))
    },

    imageLoad() {
      const headerHeight = this.$refs.titleImgRef.clientHeight
      this.imageHeight = headerHeight
    },

    startWsChecker(delay = 1000 * 5) {
      this.stopWsChecker()
      this.websocket.checkerTimer = setInterval(() => {
        const { heartbeatInterval, lastReceived } = this.websocket
        const sinceLastReceived = new Date().getTime() - (lastReceived || 0)

        if (
          this.websocket.instance === null ||
          ['INITAL', 'ERROR', 'CLOSED'].includes(this.websocket.state) ||
          (lastReceived !== null && sinceLastReceived > heartbeatInterval)
        ) {
          console.log('重连了')
          this.openWs()
        }
      }, delay)
    },
    stopWsChecker() {
      if (typeof this.websocket.checkerTimer !== 'number' || isNaN(this.websocket.checkerTimer)) { return }

      clearInterval(this.websocket.checkerTimer)
    },
    startAutoRefresh(delay = 1000 * 60) {
      this.stopAutoRefresh()
      this.autoRefresh.timer = setInterval(async() => {
        if (this.isPlaying) {
          await this.getList()
          // await this.showToday()
          this.resetPage()
        }
      }, delay)
    },
    stopAutoRefresh() {
      if (typeof this.autoRefresh.timer !== 'number' || isNaN(this.autoRefresh.timer)) { return }

      clearInterval(this.autoRefresh.timer)
    },
    startAutoScroll(delay = 1000 * 10) {
      if (!this.settingValue.autoPaging) return
      this.stopAutoScroll()
      this.autoScroll.timer = setInterval(() => {
        this.nextPage()
      }, delay)
    },
    stopAutoScroll() {
      if (typeof this.autoScroll.timer !== 'number' || isNaN(this.autoScroll.timer)) { return }

      clearInterval(this.autoScroll.timer)
    },
    resetPage() {
      this.page.currentPage = 1
    },
    toPage(page) {
      if (page < 1 && page > this.totalPage) return

      this.page.currentPage = page
    },
    nextPage(cyclePages = true) {
      if (!this.hasNextPage) {
        if (cyclePages) { this.page.currentPage = 1 }

        return
      }

      this.page.currentPage++
    },
    prevPage(cyclePages = true) {
      if (this.page.currentPage < 2) {
        if (cyclePages) this.page.currentPage = this.totalPage

        return
      }

      this.page.currentPage--
    },

    manualChangePage(type) {
      this[type]()
      this.stopAutoScroll()
      this.startAutoScroll()
    },

    pagination(e) {
      this.page.pageSize = e.limit
      this.page.currentPage = e.page
    },
    noticeTextFormat(params, index) {
      let text = ''
      Object.keys(params).forEach((k) => {
        if (k in fieldChineseMap) {
          const value = `${fieldChineseMap[k]}：${params[k]}，`
          if (!params[k]) return
          text += value
        }
      })
      const reg = /，$/gi
      text = `${index + 1}. ${text}`
      return text.replace(reg, '')
    },
    wsURL() {
      if (window.location.origin.indexOf('https://oatest.mouldc.com') > -1) {
        return 'wss://oatest.mouldc.com/wss'
      }

      if (window.location.origin.indexOf('https://oa.mouldc.com') > -1) {
        return 'wss://oa.mouldc.com/wss'
      }

      return 'wss://oatest.mouldc.com/wss'
    },
    closeWs() {
      if (['INITAL', 'ERROR', 'CLOSED'].includes(this.websocket.state)) {
        return
      }

      this.websocket.instance.close()

      this.removeStorages()
    },
    openWs() {
      if (typeof WebSocket !== 'function') throw new Error('浏览器不支持 WebSocket')

      if (['CONNECTING', 'OPENED'].includes(this.websocket.state)) return

      this.websocket.instance = new WebSocket(this.wsURL())
      this.websocket.state = 'CONNECTING'

      this.websocket.instance.onopen = () => {
        this.websocket.state = 'OPENED'
        this.websocket.lastReceived = new Date().getTime()
        this.reset()
      }

      this.websocket.instance.onmessage = (e) => {
        const data = JSON.parse(e.data)
        this.handleMessage(data)
      }

      this.websocket.instance.onerror = () => {
        this.websocket.state = 'ERROR'
      }

      this.websocket.instance.onclose = (e) => {
        console.log('e --------->', e)
        this.websocket.state = 'CLOSED'
        if (e.code !== 1000) {
          this.openWs()
        }
      }
    },
    test() {
      this.websocket.instance.close()
      // this.websocket.state = 'CLOSED'
    },
    alert(data) {
      if (!atLeast(data, ['id'])) {
        return
      }

      const index = this.record.findIndex((record) => record.id === data.id)
      // if (index === -1) { return }
      // 如果列表里已经存在就移到前面
      const noticeIndex = this.notices.findIndex((item) => item.id === data.id)
      if (noticeIndex === -1) {
        this.notices.unshift(data)
      } else {
        this.notices = [
          this.notices[noticeIndex],
          ...this.notices.filter((_, index) => index !== noticeIndex)
        ]
      }

      this.findPage(index, data)
    },

    async findPage(index, data) {
      const targetPage = Math.floor(index / this.page.pageSize) + 1
      this.toPage(targetPage)

      await this.$nextTick()

      const recordIndex = this.visitorList.findIndex((record) => record.id === data.id)
      Promise.all([this.alertRecord(recordIndex), this.alertNotice()])
    },

    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },

    async alertRecord(index) {
      if (index === -1) return
      await this.sleep(100)
      this.$refs['recordItems'][index].classList.add('flicker')
      await this.sleep(3200)
      this.$refs['recordItems'][index].classList.remove('flicker')
    },

    async alertNotice() {
      if (!this.isVisitor) return
      // this.$refs.noticeBar.resetRolling()
      this.$refs['noticeBar']?.$el?.classList?.add('flicker')
      await this.sleep(3200)
      this.$refs['noticeBar']?.$el?.classList?.remove('flicker')
    },

    async handleMessage(data) {
      this.websocket.lastReceived = new Date().getTime()

      switch (data.type) {
        case 'sendMessage':
          this.alert(data.visit)
          break

        case 'bind':
          await this.bindClient('bind', data.data)
          break

        case 'refresh':
          this.refresh()
          this.calculateItemsPerPage()
          break
      }
    },

    async bindClient(type, data) {
      console.log('data --------->', data)
      await bind({ type, client_id: data }).catch((e) => {
        throw new Error(e?.response?.data?.message ?? '绑定失败')
      })
      this.channel = data
      // this.saveStorages()
    },

    saveStorages() {
      window.localStorage.setItem(CLIENT_ID, this.channel)
    },

    getStorages() {
      return window.localStorage.getItem(CLIENT_ID)
    },

    async removeStorages() {
      await bind({ type: 'unbind', client_id: this.getStorages() }).catch((e) => {
        throw new Error(e?.response?.data?.message ?? '绑定失败')
      })
      window.localStorage.removeItem(CLIENT_ID)
    },

    async refresh() {
      this.time = ''
      await this.getList()
      // await this.showToday()
      this.resetPage()
      // this.$nextTick(() => {
      //   this.$refs.seamlessScroll?.reset?.()
      // })
    },

    // 获取当前时间
    nowDate() {
      this.timer = setInterval(() => {
        this.date = dayjs().format('YYYY-MM-DD')
        this.week = this.weekday[dayjs().day()]
        this.day = dayjs().format('HH:mm:ss')
      }, 1000)
    },
    beforeDestroy() {
      if (this.timer) {
        clearInterval(this.timer)
      }
    },
    // 获取今日来访人员
    async showToday(params) {
      try {
        this.loading = true

        const [result] = await Promise.all([
          today(this.$route.query.company_id, params),
          this.sleep(500)
        ]).catch((e) => {
          throw new Error(e?.response?.data?.message ?? '访客信息获取失败')
        })

        this.page.total = result.data.length
        this.record = result.data
        this.loading = false
        if (this.isPlaying) {
          this.startAutoScroll()
        }
      } catch (error) {
        this.loading = false
        this.$message.error(error.message)
      }
    },
    // 获取今日外出人员
    async showOut() {
      const res = await out(this.$route.query.company_id)
      this.leave = res.data
      console.log(this.leave, 666)
    },
    timeFormat(time) {
      const dateTime = dayjs(time)

      return `${dateTime.format('YYYY-MM-DD HH')}时`
      // const hour = dayjs(time).format('HH')
      // const newTime = dayjs(time).format('YYYY-MM-DD')
      // if (parseInt(hour) < 12) {
      //   return `${newTime} 上午`
      // } else {
      //   return `${newTime} 下午`
      // }
    },

    openTimePicker() {
      if (this.$refs.timePick.$el) this.$refs.timePick.$el.click()
    },

    timeChange(e) {
      console.log('e --------->', e)
      const time = [dayjs(e[0]).format('YYYY-MM-DD'), dayjs(e[1]).format('YYYY-MM-DD')]

      this.showToday({ time: JSON.stringify(time) })
    },
    reset() {
      this.page = this.$options.data().page
      this.time = ''
      this.getList()
      // this.showToday()
      this.calculateItemsPerPage()
    },
    resetNoticeList() {
      console.log('123 --------->', 123)
      this.notices = []
    },

    async getVehicleList() {
      try {
        this.loading = true
        const [result] = await Promise.all([
          getTodayAndAfterVehicleRecord(),
          this.sleep(500)
        ]).catch((e) => {
          throw new Error(e?.response?.data?.message ?? '用车记录获取失败')
        })

        this.page.total = result.data.length
        this.record = result.data
        this.loading = false
        if (this.isPlaying) {
          this.startAutoScroll()
        }
      } catch (error) {
        this.loading = false
        this.$message.error(error.message)
      }
    },

    async getReserveList() {
      this.loading = true
      try {
        const [result] = await Promise.all([
          getReserveList(),
          this.sleep(500)
        ]).catch((e) => {
          throw new Error(e?.response?.data?.message ?? '会议室预约记录获取失败')
        })

        this.page.total = result.data.length
        this.record = result.data
        console.log('record --------->', this.record)
        this.loading = false
        if (this.isPlaying) {
          this.startAutoScroll()
        }
      } catch (error) {
        this.loading = false
        this.$message.error(error.message)
      }
    },

    async getList() {
      switch (this.listType) {
        case 'visitor':
          await this.showToday()
          break
        case 'vehicleRecord':
          await this.getVehicleList()
          break
        case 'conferenceRoom':
          await this.getReserveList()
          break
      }
    },

    settingValueChange(e, type) {
      if (type === 'autoPaging') {
        this.autoPagingChange()
      } else if (type === 'autoChangeType') {
        this.autoChangeTypeChange()
      }
      this.setLocalStorage()
      console.log('e --------->', e)
      console.log('type --------->', type)
    },

    autoPagingChange() {
      if (this.settingValue.autoPaging) {
        this.startAutoScroll()
      } else {
        this.stopAutoScroll()
      }
    },

    autoChangeTypeChange() {
      if (this.settingValue.autoChangeType) {
        this.changeListTypeStart()
      } else {
        this.changeListTypeStop()
      }
    },

    getLocalStorage() {
      const value = window.localStorage.getItem(SETTING_KEY)
      if (value) return JSON.parse(value)
      return null
    },

    setLocalStorage() {
      window.localStorage.setItem(SETTING_KEY, JSON.stringify(this.settingValue))
    },

    initSettings() {
      const value = this.getLocalStorage()
      if (value) this.settingValue = { ...value }
      this.autoPagingChange()
      this.autoChangeTypeChange()
    }

  }
}
</script>
<style lang="scss" scoped>
* {
  font-family: "黑体";
}
@keyframes flicker_animation {
  0% {
    background-color: rgba(255, 255, 255, 0);
    color: #fff;
  }

  50% {
    background-color: rgba(255, 255, 255, 0.8);
    color: #333;
  }

  100% {
    background-color: rgba(255, 255, 255, 0);
    color: #fff;
  }
}

.flicker {
  animation: flicker_animation 1.8s ease-in-out 0s 2;
}

.show-visitor {
  //width: 100%;
  height: 100%;
  overflow: auto;
  background-color: #02004d;
}

.show {
  display: flex;
  flex-wrap: wrap;
}

.titleImage {
  position: relative;
  width: 100%;
  display: flex;

  .setting-icon {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
    color: #fff;
    font-size: 26px;
  }

}
.nowDate {
  font-size: 16px;
  color: #fff;
  position: absolute;
  top: 5vh;
  right: 26vh;
  font-weight: 700;
}
.frame {
  width: 100%;
  display: flex;
  margin: 0 30px;
}
.first {
  width: 100%;
  padding: 20px;
}

.interval {
  width: 2%;
}

.second {
  width: 100%;
}

.people-list-title {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #051555;
  color: #fff;
  z-index: 99;
  font-size: 30px;
  text-align: center;
  padding: 15px 0;
  margin: 20px 0 0;
  border-style: solid;
  border-width: 2px;
  border-color: #0a30a9;
  img {
    width: 12%;
    height: 30px;
  }
  .play-icon {
    padding: 0 10px;
    box-sizing: border-box;
  }
}

.list-title {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin: 0 30px;
  //flex: 1;
  text-align: center;
}

.right {
  transform: rotatey(180deg);
}

.swiper-title {
  display: flex;
  flex-wrap: wrap;
  background-color: #051555;
  color: #fff;
  position: relative;
  z-index: 99;
  border-style: solid;
  border-width: 2px;
  border-color: #0f39c9;
}

.out-title {
  display: flex;
  flex-wrap: wrap;
  font-size: 16px;
  background-color: #051555;
  color: #fff;
  position: relative;
  z-index: 99;
  border-style: solid;
  border-width: 2px;
  border-color: #0f39c9;
}

.out {
  text-align: center;
  box-sizing: border-box;
  font-size: 16px;
  padding: 15px 0;
  color: #00fff4;
}

.out-date {
  text-align: center;
  font-size: 1.3vw;
  padding: 30px 0;
  color: #fff;
}

.visitor-title {
  display: flex;
  flex: 1;
  align-items: center;
  text-align: left;
  box-sizing: border-box;
  font-size: 1.5vw;
  padding: 15px 5px;
  color: #10e0eb;
}

.warp {
  overflow: hidden;
  width: 100%;
  height: 400px;
}

.list {
  //width: 100%;
  display: flex;
  align-items: center;
  //justify-content: space-between;
  border-style: solid;
  border-width: 2px;
  border-color: #0f39c9;
  color: #fff;
  padding: 10px 0;
}

.visitor-content {
  flex: 1;
  text-align: left;
  font-size: 1.4vw;
  padding: 20px 5px;
  word-break: break-word;
  font-weight: 700;
}

.timePick {
  position: absolute;
  top: 0;
  visibility: hidden;
  width: 1px;
}

.of {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}

::v-deep(.el-scrollbar__thumb) {
  background-color: rgba(144, 147, 153, 1);
}

.rotate {
  animation: rotate-animation 1s linear infinite both;
}

@keyframes rotate-animation {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(-360deg);
  }
}

::v-deep(.el-pagination__total) {
  color: #fff;
}

::v-deep(.el-pagination__jump) {
  color: #fff;
}
.pages {
  width: 100%;
  display: flex;
  justify-content: center;
}

.list-warp {
  //height: 100vh;
}

.setting-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.setting-drawer {
  padding: 0 20px;

  &__item{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 0;
    &-title {
      font-family: 'Microsoft YaHei';
      color: rgba(0, 0, 0, .5);
    }
  }
}

.dropdown-btn {
  cursor: pointer;
  margin-left: 10px;
  color: #fff;
}

</style>
